import { useEffect,useState } from "react";

import "./App.css";
import {useWindowSize} from "./useWidowSize"

function App() {
  const [count, setCount] = useState(0);
  const [user, setUser] = useState({ name: "react", age: 18 });
  const [total,setTotal] = useState(0)
  const handleUser = () => {
    // setUser({ name: "vue", age: 188 });
    setUser({ ...user, age: 188 });
  };
  const [list, setList] = useState(["tom", "jack"]);
  const handleArray = () => {
    setList([...list, "dd"]);
  };
  const hanleCount = () => {
    // setCount(count + 1);
    setTimeout(() => {
      setCount(count + 1);
    });
  };
  useEffect(()=>{
    document.title = 'React后台'
  })
  //
  useEffect(()=>{
    setCount(count+1)
  },[])

  useEffect(()=>{
    setTotal(count*5)
  },[count])

  // 及时清除定时器
  useEffect(()=>{
    const T = setInterval(()=>{
      // count 此时为闭包
      // setCount(count + 1)
      setCount(count => count + 1)
    },1000)
    return ()=>{
      clearInterval(T)
    }
  },[])

  // // 获取窗口
  // const [size,setSize] = useState({
  //   width: document.documentElement.clientWidth,
  //   height:document.documentElement.clientHeight
  // })

  // const handleResize = () =>{
  //   setSize({
  //     width: document.documentElement.clientWidth,
  //     height:document.documentElement.clientHeight
  //   })
  // }

  // useEffect(()=>{
  //   window.addEventListener('resize',handleResize)
  //   // return是回调函数
  //   return()=>{
  //     window.removeEventListener('resize',handleResize)
  //   }
  //   // []
  // },[])

    // const [size] = useWindowSize()
    const size = useWindowSize()

  return (
    <>
      <div className="card">
        <button onClick={() => setCount((count) => count + 1)}>
          count is {count}
        </button>
      </div>
      <div>
        <p>
          <span>姓名：{user.name}</span>
          <span>年龄：{user.age}</span>
        </p>
        <button onClick={handleUser}>修改用户</button>
      </div>
      <div>
        {list.map((item) => {
          return <span style={{ color: "red", marginLeft: 10 }}>{item}</span>;
        })}
      </div>
      <button onClick={handleArray}>修改数组数据</button>
      <div className="card">
        <button onClick={hanleCount}>count is {count}</button>
      </div>
      <div>count:{count}</div>
      <div>total:{total}</div>
      <p>
        window width: {size.width}  window height: {size.height}
      </p>
    </>
  );
}

export default App;
